﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.Analytics;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class PlayController : MonoBehaviour
{
    /// <summary>
    /// 是否向左移动
    /// </summary>
    private bool isMoveLeft = false;
    /// <summary>
    /// 当前是否在跳跃
    /// </summary>
    private bool isJuming = false;
    private Vector3 nextPlatformLeft, nextPlatformRight;
    private ManagerVars vars;
    /// <summary>
    /// 玩家的射线
    /// </summary>
    private Rigidbody2D my_Body;
    public Transform rayDowm,rayLeft,rayRight;//检测物体
    public LayerMask platformLayer,obstacleLayer;//检测层级
    /// <summary>
    /// //一个Sprite游戏对象，至少拥有两个组件，Transform组件和Sprite Renderer组件。
    /// 在Scene中渲染显示出图像
    /// </summary>
    private SpriteRenderer spriteRenderer;
    private bool isMove=false;//玩家是否移动
    /// <summary>
    /// 音效
    /// </summary>
    private AudioSource m_AudioSource;

    private void Awake()
    {
        //广播监听 -有没有更换皮肤
        EventCenter.AddListener<int>(EventDefine.ChangeSkin,ChangeSkin);
        EventCenter.AddListener<bool>(EventDefine.IsMusicOn, IsMusicOn);

        vars = ManagerVars.GetManagerVars();
        my_Body = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        m_AudioSource = GetComponent<AudioSource>();
    }
    private void OnDestroy()
    {
        EventCenter.RemoveListener<int>(EventDefine.ChangeSkin, ChangeSkin);
        EventCenter.RemoveListener<bool>(EventDefine.IsMusicOn, IsMusicOn);
    }
    private void Start()
    {
        ChangeSkin(GameManager.Instance.GetSelectedSkin());
    }
    /// <summary>
    /// 更换皮肤的调用
    /// </summary>
    /// <param name="skinIndex"></param>
    private void ChangeSkin(int skinIndex)
    {
        spriteRenderer.sprite = vars.characterSkinSpriteList[skinIndex];
    }
    /// <summary>
    /// 音效是否开启
    /// </summary>
    /// <param name="skinIndex"></param>
    private void IsMusicOn(bool value)
    {
        m_AudioSource.mute = !value;
    }
    /// <summary>
    /// 手机检测UI面板
    /// </summary>
    /// <param name="mousePosition"></param>
    /// <returns></returns>
    private bool IsPointerOverGameObject(Vector2 mousePosition) 
    {
        //创建一个点击事件
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.position = mousePosition;
        List<RaycastResult> raycastResults = new List<RaycastResult>();
        //向点击事件发射一条射线，检测是否有点击UI
        EventSystem.current.RaycastAll(eventData,raycastResults);

        return raycastResults.Count > 0;
    }
    // Update is called once per frame
    void Update()
    {
        Debug.DrawRay(rayDowm.position, Vector2.down * 1, Color.red);
        Debug.DrawRay(rayLeft.position, Vector2.left * 0.15f, Color.red);
        Debug.DrawRay(rayRight.position, Vector2.right * 0.15f, Color.red);
        /**

        //点击UI不进行跳跃  是否碰到UI
         * TODO手机上遇到的问题
         * 解决手机端判断手指是否在UI上失效的问题
         */
        /** if (Application.platform==RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
        //    //如果当前运行平台是安卓或苹果
        //{
        //    int fingerId = Input.GetTouch(0).fingerId;
        //    //方法IsPointerOverGameObject拿到手指的Id
        //    if (EventSystem.current.IsPointerOverGameObject(fingerId)) return ;
        //}
        //else
        //{
        //     if (EventSystem.current.IsPointerOverGameObject()) return;
        //}
        */

        if (IsPointerOverGameObject(Input.mousePosition)) return;
        //匹配手机上的返回键
        if (Input.GetKeyDown(KeyCode.Escape))
        {
                //退出app，，（发布出来才好用）
                Application.Quit();
        }

        //判断游戏满足开始，没有结束  当前游戏是暂停的  这一条件
        if (GameManager.Instance.IsGameStarted==false||
            GameManager.Instance.IsGameOver ||
            GameManager.Instance.IsPaused)
            return;
        
        //检测到触摸屏幕
        if (Input.GetMouseButtonDown(0) && isJuming==false && nextPlatformLeft!=Vector3.zero)
        //屏幕点击 没有跳跃 位置不为0,0（新＋的，之前再来一局跳两次）
        {
            if (isMove==false)
            {
                EventCenter.Broadcast(EventDefine.PlayerIsMove);
                isMove = true;
            }
            //播放跳跃的音效  -传入片段  managerVars中定义
            m_AudioSource.PlayOneShot(vars.jumpClip);
            EventCenter.Broadcast(EventDefine.DecidePath);//广播 
            isJuming = true;
            Vector3 mousePos = Input.mousePosition;

            //点击的是左边屏幕
            if (mousePos.x<Screen.width/2)
            {
                isMoveLeft = true;
            }
            else if (mousePos.x>Screen.width/2)
            {
                isMoveLeft = false;
            }
            Jump();
        }

        //游戏结束了
        if (my_Body.velocity.y < 0 && IsRayPlatform() == false && GameManager.Instance.IsGameOver == false)
        //玩家往下落 没有检测到平台 游戏没有结束
        {
            //播放死亡音效
            m_AudioSource.PlayOneShot(vars.fallClip);
            //人物
            spriteRenderer.sortingLayerName = "Default";
            GetComponent<BoxCollider2D>().enabled = false;
            GameManager.Instance.IsGameOver = true;
            print("游戏结束IsRayPlatform");
            //游戏结束面板
            StartCoroutine(DealyShowGameOverPanel());
        }
        if (isJuming && IsRayObstacle() && GameManager.Instance.IsGameOver==false)
        //正在跳跃 检测到障碍物 游戏没有结束
        {
            m_AudioSource.PlayOneShot(vars.hitClip);
            print("游戏结束IsRayObstacle");
            GameObject go = ObjectPool.Instance.GetDeathEffect();
            go.SetActive(true);//显示特效
            //TODO 粒子的显示位置不正确
            go.transform.position = transform.position;
            GameManager.Instance.IsGameOver = true;

            //TODO 销毁实例就不能用
            //EventCenter.Broadcast(EventDefine.ShowGameOverPanel);
            //Destroy(gameObject);
            spriteRenderer.enabled = false;
            StartCoroutine(DealyShowGameOverPanel());
        }
        //第三种游戏结束
        if (transform.position.y-Camera.main.transform.position.y<-6 && GameManager.Instance.IsGameOver==false)
        {
            m_AudioSource.PlayOneShot(vars.fallClip);
            GameManager.Instance.IsGameOver = true;
           StartCoroutine(DealyShowGameOverPanel());
            print("游戏结束了-你太慢了");
        }
    }
    IEnumerator DealyShowGameOverPanel() 
    {
      yield return new WaitForSeconds(1f);//不能大于PlatformSprite脚本中携程等待时间
        //调用携程广播事件码
        EventCenter.Broadcast(EventDefine.ShowGameOverPanel);
       // GameOver.Instance.OpenPanel();//方法二：打开面板
    }
    /// <summary>
    /// 反转
    /// 使用Dotween
    /// </summary>
    private void Jump() 
    {
        if (isMoveLeft)
        {
            transform.localScale = new Vector3(-1,1,1);
            transform.DOMoveX(nextPlatformLeft.x,0.2f);
            transform.DOMoveY(nextPlatformLeft.y+0.8f,0.15f);//具有跳跃效果
        }
        else
        {
            transform.localScale = Vector3.one;
            transform.DOMoveX(nextPlatformRight.x, 0.2f);
            transform.DOMoveY(nextPlatformRight.y + 0.8f, 0.15f);//具有跳跃效果
        }
    }
    /// <summary>
    /// 碰撞检测
    /// </summary>
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Platform")
        {
            isJuming = false;
            //计算出下一个平台的位置
            Vector3 currentPlatformPos = collision.gameObject.transform.position;
            nextPlatformLeft = new Vector3(currentPlatformPos.x-vars.nextXPos,currentPlatformPos.y+vars.nextYPos,0);
            nextPlatformRight = new Vector3(currentPlatformPos.x + vars.nextXPos, currentPlatformPos.y + vars.nextYPos, 0);
        }
    }
    //下一个平台
    private GameObject lastHitGo = null;
    /// <summary>
    /// 射线检测是否检测到平台--死亡
    /// </summary>
    /// <returns></returns>
    private bool IsRayPlatform()
    {
        //人物位置 方向 距离 检测层级 
      RaycastHit2D hit= Physics2D.Raycast(rayDowm.position,Vector2.down,1f,platformLayer);
        if (hit.collider!=null)
        {
            if (hit.collider.tag == "Platform")//碰撞到平台
            {
                if (lastHitGo!=hit.collider.gameObject)
                    //避免在一个平台上重复广播事件
                {
                    if (lastHitGo == null)
                    {//第一次   不增加成绩
                        lastHitGo = hit.collider.gameObject;
                        return true;
                    }
                    //广播事件码  每帧调用  
                    EventCenter.Broadcast(EventDefine.AddScore);
                    lastHitGo = hit.collider.gameObject;
                }
              return true;
            }        
        }
        return false;
    }
    /// <summary>
    /// 是否检测到障碍物-直接消失
    /// </summary>
    /// <returns></returns>
    private bool IsRayObstacle() 
    {
        RaycastHit2D leftHit = Physics2D.Raycast(rayLeft.position, Vector2.left, 0.15f, obstacleLayer);
        RaycastHit2D rightHit = Physics2D.Raycast(rayRight.position, Vector2.right, 0.15f, obstacleLayer);
     
        if (leftHit.collider!=null)
        {
           
            if (leftHit.collider.tag == "Obstacle")
                return true;  
        }
        if (rightHit.collider != null)
        {
            if (rightHit.collider.tag == "Obstacle")
                return true;
        }
        return false;
    }
    /// <summary>
    /// 都没有勾选isTriggen
    /// 次碰撞器刚体接触到另个刚体
    /// </summary>
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag=="Picker")
        {
            //播放吃钻石音效
            m_AudioSource.PlayOneShot(vars.diamondClip);
            //吃到钻石-隐藏
            collision.gameObject.SetActive(false);
            //广播事件码
            EventCenter.Broadcast(EventDefine.AddDiamond);
        }
    }
}
